package my.union;

/**
 * 并查集顶层公共父类
 *
 * @author AJun
 * @date 2020/11/1
 */
public abstract class AbstractUnionFind implements UnionFind {

    /**
     * 存储并查集元素的父节点
     */
    protected int[] parents;

    public AbstractUnionFind(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("Capacity must >= 1");
        }

        parents = new int[capacity];
        for (int i = 0; i < parents.length; i++) {
            parents[i] = i;
        }
    }

    /**
     * 检查v1、v2是否属于同一个集合
     */
    @Override
    public boolean isSame(int v1, int v2) {
        return find(v1) == find(v2);
    }

    protected void rangeCheck(int v) {
        if (v < 0 || v >= parents.length) {
            throw new IllegalArgumentException("v is out of bounds");
        }
    }

}
